package cn.itcast.goods.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.exception.DeletionNotAllowedException;
import cn.itcast.goods.dto.DishDTO;
import cn.itcast.goods.dto.DishPageQueryDTO;
import cn.itcast.goods.mapper.DishFlavorMapper;
import cn.itcast.goods.mapper.DishMapper;
import cn.itcast.goods.mapper.SetmealDishMapper;
import cn.itcast.goods.mapper.SetmealMapper;
import cn.itcast.goods.pojo.Dish;
import cn.itcast.goods.pojo.DishFlavor;
import cn.itcast.goods.pojo.Setmeal;
import cn.itcast.goods.pojo.SetmealDish;
import cn.itcast.goods.service.DishService;
import cn.itcast.goods.vo.DishVO;
import cn.itcast.result.PageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品和口味
     *
     * @param dto
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dto) {
        //分两步走,先添加菜品，再添加口味，顺序不能变，因为没有菜品的话添加不了口味。
        //添加菜品后有一个回显id，用于与口味关联
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.Insert(dish);

        List<DishFlavor> flavors = dto.getFlavors();
        flavors.forEach(e -> {
            e.setDishId(dish.getId());
            dishFlavorMapper.insert(e);
        });


        return;
    }

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageBean pageQuery(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dto);

        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Integer> ids) {
        if (ids == null) {
            return;
        }
        //启动的菜品不能删
        List<Dish> dishes = dishMapper.getStartById(ids);
        if (dishes.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //关联的菜品不能删
        List<SetmealDish> setmealDishes = setmealDishMapper.getByDishId(ids);
        if (setmealDishes.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //要删除菜品的基本信息，删除菜品的口味列表信息
        dishMapper.delete(ids);
        dishFlavorMapper.deleteByDishId(ids);

    }

    /**
     * 根据id查询菜品和口味
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Integer id) {
        DishVO dishVO = dishMapper.getByIdWithFlavor(id);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dto
     */
    @Transactional
    @Override
    @CacheEvict(cacheNames = "dish:getDishVOByCategoryId", allEntries = true)
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //修改dish表
        dishMapper.update(dish);
        //根据菜品id删除口味
        dishFlavorMapper.deleteByDishId(Arrays.asList(dish.getId().intValue()));
        //添加口味
        List<DishFlavor> flavors = dto.getFlavors();
        flavors.forEach(o -> {
            dishFlavorMapper.insert(o);
        });

        return;
    }

    /**
     * 菜品起售、停售
     *
     * @param id
     * @param status
     */
    @Override
    @Transactional
    public void statrtOrStop(Long id, Integer status) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);

        dishMapper.update(dish);
        //  - 业务：如果是停售菜品，菜品关联的套餐也需要停售
        if (status == 0) {
            //根据菜品id查询套餐id
            List<SetmealDish> byDishId = setmealDishMapper.getByDishId(Arrays.asList(id.intValue()));
            //将查询到的所有套餐全部停售
            byDishId.forEach(o -> {
                Setmeal setmeal = Setmeal.builder()
                        .id(o.getSetmealId())
                        .status(status)
                        .build();
                setmealMapper.update(setmeal);
            });

        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Integer categoryId) {
        List<Dish> dishs = dishMapper.getByCategoryId(categoryId);
        return dishs;
    }

    /**
     * 根据分类id查询菜品（包含口味）
     *  cacheNames: redis的key前缀
     *  key: redis的key部分，RedisKey = cacheNames + key
     *  condition: 存放的是表达式,true或者fales， true标识将结果存入缓存，false不存(不能使用result)
     *  unless：跟condition相反
     *  condition与unless有什么区别：condition可以理解为前置通知，unless可以理解为环绕通知
     *
     * @param categoryId
     * @return
     */
    @Override
    @Cacheable(cacheNames = "dish:getDishVOByCategoryId", key = "#categoryId", unless="#result == null")
    public List<DishVO> getDishVOByCategoryId(Integer categoryId) {
        List<DishVO> dishVOS = dishMapper.getDishVOByCategoryId(categoryId);
        return dishVOS;
    }

    /**
     * 根据id查询dish
     *
     * @param dishId
     * @return
     */
    @Override
    public Dish getById(Long dishId) {
        return dishMapper.getById(dishId);
    }
}
